/** @file    FormDeviceManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormDeviceManager.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormDeviceManager class.
 * The header for this class can be found in FormDeviceManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormDeviceManager.h"
 #include "ui_FormDeviceManager.h"
 #include <core/DeviceManager.h>

 #include <QtGui/QCompleter>
 #include <QtGui/QMessageBox>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormDeviceManager, "wosh::gui::IWidgetGeneric", 1.0, _static_FormDeviceManager )
 WOSH_GUI_MAP(wosh::gui::FormDeviceManager, "wosh::DeviceManager", 0.0, _static_Map_FormDeviceManager )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormDeviceManager::FormDeviceManager(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormDeviceManager();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_DeviceManager_URI);
	buildMenus();

	// tab Devices [0]
	this->m_ui->tableViewDevices->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewDevices, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewDevices, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableViewDevices_ContextMenu(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->tableViewDevices->getTableView(), SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(tableViewDevices_doubleClicked(const QModelIndex&)));
	connect(this->m_ui->btnRegisterNew, SIGNAL(clicked()), this, SLOT(btnRegisterNew_clicked()));
	connect(this->m_ui->btnUnRegister, SIGNAL(clicked()), this, SLOT(btnUnRegister_clicked()));

	// tab EventsLog [1]
	this->m_ui->tableViewEventsLog->setMethodList(_DeviceManager_METHOD_eventslog);
	this->m_ui->tableViewEventsLog->setResizeStretch(1);
	this->m_ui->tableViewEventsLog->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewEventsLog, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewEventsLog, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableViewEventsLog_ContextMenu(const QPoint&, const QModelIndex&)) );
	this->mapMethodButton(_DeviceManager_METHOD_clear_log, this->m_ui->btnClearLog);
	connect(this->m_ui->chkMonitorDeviceBus, SIGNAL(clicked()), this, SLOT(chkMonitorDeviceBus_clicked()));
	this->propMapperCfg = new PropertiesMapper(this, true);
	connect(this->propMapperCfg, SIGNAL(send_request(const QString&, ISerializable*)), this, SLOT(executeRemoteMethod(const QString&, ISerializable*)));
	this->propMapperCfg->set(_DeviceManager_KEY_EventLogMaxSize, this->m_ui->spinEventLogSize);
	this->propMapperCfg->set(_DeviceManager_KEY_EventLogLocallyOnly, this->m_ui->chkRecordLocalEvents);

	// tab Fake Event [2]
	QCompleter* completerURI = new QCompleter(this);
	completerURI->setCaseSensitivity(Qt::CaseInsensitive);
	completerURI->setModel( this->m_ui->tableViewDevices->getTableModel() );
	completerURI->setCompletionColumn(0);
	this->m_ui->txtEmulateDeviceName->setCompleter(completerURI);
	QCompleter* completerEvent = new QCompleter(this);
	completerEvent->setCaseSensitivity(Qt::CaseInsensitive);
	completerEvent->setModel( this->m_ui->tableViewEventsLog->getTableModel() );
	completerEvent->setCompletionColumn(2);
	this->m_ui->txtEmulateEventName->setCompleter(completerEvent);
	QCompleter* completerData = new QCompleter(this);
	completerData->setCaseSensitivity(Qt::CaseInsensitive);
	completerData->setModel( this->m_ui->tableViewEventsLog->getTableModel() );
	completerData->setCompletionColumn(3);
	this->m_ui->txtEmulateData->setCompleter(completerData);
	connect(this->m_ui->btnEmulateEvent, SIGNAL(clicked()), this, SLOT(btnEmulateEvent_clicked()));
 }

FormDeviceManager::~FormDeviceManager() {
	delete this->m_ui;
 }

void FormDeviceManager::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::refreshAll() {
	this->setWindowTitle( QString("Device Manager [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	this->m_ui->tableViewDevices->refreshData();
	this->m_ui->tableViewEventsLog->refreshData();
	refreshConfiguration();
 }

void FormDeviceManager::refreshConfiguration() {
	List* dlProps = this->propMapperCfg->createKeysList();
	executeRemoteMethod( _METHOD_GetProperties, dlProps );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::btnEmulateEvent_clicked() {
	List* dl = new List(3);
	URI uri_src;
	uri_src.fromString(this->m_ui->txtEmulateDeviceName->text().toLatin1().data());
	if ( uri_src.isValid() && !uri_src.getName().empty() )
		dl->push_back<Variant>( uri_src.getName() );
	else
		dl->push_back<Variant>( this->m_ui->txtEmulateDeviceName->text().toLatin1().data() );
	dl->push_back<Variant>( this->m_ui->txtEmulateEventName->text().toLatin1().data() );
	dl->push_back<Variant>( this->m_ui->txtEmulateData->text().toLatin1().data() );
	executeRemoteMethod( _DeviceManager_METHOD_fake_event, dl );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::btnRegisterNew_clicked() {
	Device* dev = NULL;
	executeRemoteMethod( _DeviceManager_METHOD_register, dev );
}

void FormDeviceManager::btnUnRegister_clicked() {
	const ISerializable* iUri = this->m_ui->tableViewDevices->getTableView()->getItem( this->m_ui->tableViewDevices->getTableView()->currentIndex().row(), 0 );
	if ( iUri == NULL || !iUri->isKindOf<URI>() )
		return;
	string devName = iUri->as<URI>()->getName();
	executeRemoteMethod( _DeviceManager_METHOD_unregister, new Variant(devName) );
}

void FormDeviceManager::tableViewDevices_doubleClicked( const QModelIndex& index ) {
	const ISerializable* iUri = this->m_ui->tableViewDevices->getTableView()->getItem( index.row(), 0 );
	if ( iUri == NULL || !iUri->isKindOf<URI>() )
		return;
	Variant vType = this->m_ui->tableViewDevices->getTableView()->getItemAsVariant(index.row(), 1);
	QStringList ints;
	emit request_create_GUI(iUri->as<URI>()->getName(),vType.toString(), *iUri->as<URI>(), ints );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::chkMonitorDeviceBus_clicked() {
	if ( this->m_ui->chkMonitorDeviceBus->isChecked() ) {
		BusDevices.setMessageHandler(this);
		WRESULT bus_d_connected = BusDevices.connect( _Bus_Devices );
		if ( WFAILED(bus_d_connected) )
			QMessageBox::warning(this, this->windowTitle(), tr("FAILED#%d Connecting Device Bus!").arg(bus_d_connected) );
	 }
	else {
		WRESULT bus_d_disconnected = BusDevices.disconnect();
		if ( WFAILED(bus_d_disconnected) )
		QMessageBox::warning(this, this->windowTitle(), tr("FAILED#%d Disconnecting Device Bus!").arg(bus_d_disconnected) );
	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::buildMenus() {
	this->menuDeviceTitle = new QAction(this);
	this->menuDeviceTitle->setEnabled(false);
	this->menuDeviceForceUpdate = new QAction(this);
	this->menuDeviceForceUpdate->setText(tr("&Force Update"));
	this->menuDevice = new QMenu(this);
	this->menuDevice->addAction(this->menuDeviceTitle);
	this->menuDevice->addSeparator();
	this->menuDevice->addAction(this->menuDeviceForceUpdate);

	this->menuEventLogTitle = new QAction(this);
	this->menuEventLogTitle->setEnabled(false);
	this->menuEventLogRePlay = new QAction(this);
	this->menuEventLogRePlay->setText(tr("&Re-Play Event"));
	this->menuEventLogFillSheet = new QAction(this);
	this->menuEventLogFillSheet->setText(tr("&Fill Emulate-Event sheet.."));
	this->menuEventLog = new QMenu(this);
	this->menuEventLog->addAction(this->menuEventLogTitle);
	this->menuEventLog->addSeparator();
	this->menuEventLog->addAction(this->menuEventLogRePlay);
	this->menuEventLog->addAction(this->menuEventLogFillSheet);
 }

void FormDeviceManager::tableViewDevices_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() ) return;
	Variant deviceName;// = this->m_ui->tableViewDevices->getCurrentItemAsVariantAtCol(0);
	Variant deviceType = this->m_ui->tableViewDevices->getCurrentItemAsVariantAtCol(1);
	this->menuDeviceTitle->setText( deviceName.toString().c_str() );
	this->menuDeviceTitle->setIcon( GuiUtilities::createIconFor(deviceType.toString()) );
	QAction* selected = this->menuDevice->exec( globalPos );
	if ( selected == this->menuDeviceForceUpdate ) {
	 }
 }

void FormDeviceManager::tableViewEventsLog_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() ) return;
	const URI* deviceURI = this->m_ui->tableViewEventsLog->getTableView()->getItem<URI>(index.row(), 1);
	Variant deviceName("-");
	if ( deviceURI != NULL )
		deviceName = deviceURI->getName();
	this->menuEventLogTitle->setText( deviceName.toString().c_str() );

	//Variant deviceType = this->m_ui->tableViewEventsLog->getCurrentItemAsVariantAtCol(1);
	//this->menuEventLogTitle->setIcon( GuiUtilities::createIconFor(deviceType.toString()) );
	this->menuEventLogTitle->setIcon( GuiUtilities::createIconFor(Device::className()) );

	QAction* selected = this->menuEventLog->exec( globalPos );
	if ( selected == this->menuEventLogRePlay ) {
		Variant eventName = this->m_ui->tableViewEventsLog->getCurrentItemAsVariantAtCol(2);
		Variant eventData = this->m_ui->tableViewEventsLog->getCurrentItemAsVariantAtCol(3);
		List* dl = new List(3);
		dl->push_back( deviceName.clone() );
		dl->push_back( eventName.clone() );
		dl->push_back( eventData.clone() );
		executeRemoteMethod( _DeviceManager_METHOD_fake_event, dl );
	 }
	else if ( selected == this->menuEventLogFillSheet ) {
		Variant eventName = this->m_ui->tableViewEventsLog->getCurrentItemAsVariantAtCol(2);
		Variant eventData = this->m_ui->tableViewEventsLog->getCurrentItemAsVariantAtCol(3);

		this->m_ui->txtEmulateDeviceName->setText( deviceURI->toString().c_str() );
		this->m_ui->txtEmulateEventName->setText( eventName.toString().c_str() );
		this->m_ui->txtEmulateData->setText( eventData.toString().c_str() );
		this->m_ui->tabWidget->setCurrentIndex(2);
	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormDeviceManager::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() ) return;
	if ( message.getSourceBus() == _Bus_Devices ) { // WARNING, this is not thread-safe, here can't update any gui
		if ( !message.getContent()->isFact() ) return;
		executeRemoteMethod( _DeviceManager_METHOD_eventslog );
		return;
	 }
	if ( !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableViewDevices->evalResponse(response);
	this->m_ui->tableViewEventsLog->evalResponse(response);

	if ( response->getMethod() == _DeviceManager_METHOD_fake_event ) {
		if ( WFAILED(response->getReturnValue()) )
			QMessageBox::warning(this, this->windowTitle(), tr("FAILED#%d sending Device Event!").arg(response->getReturnValue()) );
		else {
			this->m_ui->tableViewEventsLog->refreshData();
			QMessageBox::information(this, this->windowTitle(), tr("Device Event has been sent!") );
		 }
		return;
	 }

	this->propMapperCfg->evalResponse(response);

	if ( response->getMethod() == _DeviceManager_METHOD_clear_log && WSUCCEEDED(response->getReturnValue()) )
		this->m_ui->tableViewEventsLog->refreshData();

	promptMethodResponse(message);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
